<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="超市" prop="supermarketId">
        <el-select
          v-model="queryParams.supermarketId"
          @keyup.enter.native="handleQuery"
          placeholder="请选择超市"
        >
          <el-option
            v-for="item in supermarketOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="classificationId">
        <el-select
          v-model="queryParams.classificationId"
          filterable
          @keyup.enter.native="handleQuery"
          placeholder="请选择分类"
        >
          <el-option
            v-for="item in classificationOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="区域" prop="ownRegionId">
        <el-select
          v-model="queryParams.ownRegionId"
          @keyup.enter.native="handleQuery"
          placeholder="请选择区域"
        >
          <el-option
            v-for="item in regionOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="生产商" prop="producer">
        <el-input
          v-model="queryParams.producer"
          placeholder="请输入生产商"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input
          v-model="queryParams.brand"
          placeholder="请输入品牌"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        <el-form-item label="上架时间">
            <el-date-picker
              v-model="dateRange.shelfTime"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="下架时间">
            <el-date-picker
              v-model="dateRange.downTime"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="过期时间">
            <el-date-picker
              v-model="dateRange.expiratTime"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['supermarket:commodity:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['supermarket:commodity:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['supermarket:commodity:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['supermarket:commodity:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="commodityList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="商品编号"
        align="center"
        prop="id"
        v-if="columns[0].visible"
      />
      <el-table-column
        label="超市"
        align="center"
        prop="supermarketName"
        v-if="columns[1].visible"
      />
      <el-table-column
        label="名称"
        align="center"
        prop="name"
        v-if="columns[2].visible"
      />
      <el-table-column
        label="分类"
        align="center"
        prop="classificationName"
        v-if="columns[3].visible"
      />
      <el-table-column
        label="区域"
        align="center"
        prop="regionName"
        v-if="columns[5].visible"
      />
      <el-table-column
        label="价格"
        align="center"
        prop="price"
        v-if="columns[4].visible"
      />
      <el-table-column
        label="图片"
        align="center"
        prop="picture"
        v-if="columns[6].visible"
      >
        <template slot-scope="scopephoto">
          <image-preview
            style="width: 80px; height: 80px"
            :src="scopephoto.row.picture"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="质量"
        align="right"
        prop="quality"
        v-if="columns[7].visible"
      />
      <el-table-column 
        label="质量单位"
        align="left"
        prop="qualityUnit"
        >
        <template slot-scope="scope">
    <dict-tag :options="dict.type.commodity_quality_unit" :value="scope.row.qualityUnit"/>
  </template>
      </el-table-column>

      <el-table-column
        label="库存"
        align="center"
        prop="inventory"
        v-if="columns[8].visible"
      />
      <el-table-column 
        label="库存单位"
        align="left"
        prop="qualityUnit"
        >
        <template slot-scope="scope">
    <dict-tag :options="dict.type.commodity_quality_unit" :value="scope.row.qualityUnit"/>
  </template>
      </el-table-column>
      <el-table-column
        label="生产商"
        align="center"
        prop="producer"
        v-if="columns[9].visible"
        :resizable =true
      />
      <el-table-column
        label="品牌"
        align="center"
        prop="brand"
        v-if="columns[10].visible"
      />
      <el-table-column
        label="商品过期时间"
        align="center"
        prop="expiratTime"
        width="180"
        v-if="columns[13].visible"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expiratTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="上架时间"
        align="center"
        prop="shelfTime"
        width="180"
        v-if="columns[11].visible"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.shelfTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="下架时间"
        align="center"
        prop="downTime"
        width="180"
        v-if="columns[12].visible"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.downTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="备注"
        align="center"
        prop="remarks"
        v-if="columns[14].visible"
      />
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="700px"
      label-width="auto"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="超市" prop="supermarketId">
          <el-select
            v-model="form.supermarketId"
            filterable
            placeholder="请选择超市"
            @change="hangleNameBySupermarketId"
          >
            <el-option
              v-for="item in supermarketOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="classificationId">
          <el-select
            v-model="form.classificationId"
            filterable
            placeholder="请选择分类"
          >
            <el-option
              v-for="item in newClassificationOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.status == 1 ? true : false"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区域" prop="ownRegionId">
          <el-select
            v-model="form.ownRegionId"
            filterable
            placeholder="请选择区域"
          >
            <el-option
              v-for="item in newRegionOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.status == 1 ? true : false"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item>

        <el-form-item label="质量" prop="quality">
          <el-input
            placeholder="请输入质量"
            v-model="form.quality"
            class="input-with-select"
          >
            <el-select class="search"
              v-model="form.qualityUnit"
              slot="append"
              placeholder="请选择"
            >
              <el-option
                v-for="dict in dict.type.commodity_quality_unit"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-input>
        </el-form-item>

        <el-form-item label="生产商" prop="producer">
          <el-input v-model="form.producer" placeholder="请输入生产商" />
        </el-form-item>
    
        <el-form-item label="库存" prop="inventory">
          <el-input
            placeholder="请输入库存"
            v-model="form.inventory"
            class="input-with-select"
          >
            <el-select class="search"
              v-model="form.qualityUnit"
              slot="append"
              placeholder="请选择"
            >
              <el-option
                v-for="dict in dict.type.commodity_quality_unit"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-input>
        </el-form-item>

        <el-form-item label="品牌" prop="brand">
          <el-input v-model="form.brand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="上架时间" prop="shelfTime">
          <el-date-picker
            clearable
            v-model="form.shelfTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择上架时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="下架时间" prop="downTime">
          <el-date-picker
            clearable
            v-model="form.downTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择下架时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="过期时间" prop="expiratTime">
          <el-date-picker
            clearable
            v-model="form.expiratTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择过期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="图片" prop="picture">
          <image-upload v-model="form.picture" :limit="1" />
        </el-form-item>
        <br />
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="form.remarks"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCommodity,
  getCommodity,
  delCommodity,
  addCommodity,
  updateCommodity,
} from "@/api/supermarket/commodity";
import { getSupermarketName } from "@/api/supermarket/supermarket";
import { getRegionName } from "@/api/supermarket/region";
import { getClassificationName } from "@/api/supermarket/classification";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Commodity",
  dicts: ['commodity_quality_unit'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      commodityList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //超市选项
      supermarketOptions: [],
      // 分类选项
      classificationOptions: [],
      // 过滤掉的新分类
      newClassificationOptions: [],
      // 区域选项
      regionOptions: [],
      // 过滤掉的新区域
      newRegionOptions: [],

        // 日期范围
        dateRange: {
          shelfTime: [],
          downTime: [],
          expiratTime: [],
        },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supermarketId: null,
        name: null,
        classificationId: null,
        price: null,
        ownRegionId: null,
        picture: null,
        quality: null,
        inventory: null,
        producer: null,
        brand: null,
        remarks: null,
      },
      // 表单参数
      form: {},

      columns: [
        { key: 0, label: `商品编号`, visible: true },
        { key: 1, label: `超市名称`, visible: true },
        { key: 2, label: `名称`, visible: true },
        { key: 3, label: `分类`, visible: true },
        { key: 4, label: `价格`, visible: true },
        { key: 5, label: `区域`, visible: true },
        { key: 6, label: `图片`, visible: true },
        { key: 7, label: `质量`, visible: true },
        { key: 8, label: `库存`, visible: true },
        { key: 9, label: `生产商`, visible: true },
        { key: 10, label: `品牌`, visible: true },
        { key: 11, label: `上架时间`, visible: true },
        { key: 12, label: `下架时间`, visible: true },
        { key: 13, label: `过期时间`, visible: true },
        { key: 14, label: `备注`, visible: true },
      ],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          {
            min: 0,
            max: 50,
            message: "长度在 30 到 50 个字符",
            trigger: "blur",
          },
        ],
        supermarketId: [
          { required: true, message: "请选择超市名称", trigger: "change" },
        ],
        shelfTime: [
          { required: true, message: "请选择日期", trigger: "change" },
        ],
        expiratTime: [
          { required: true, message: "请选择日期", trigger: "change" },
        ],
        ownRegionId: [
          { required: true, message: "请选择区域", trigger: "change" },
        ],
        classificationId: [
          { required: true, message: "请选择分类", trigger: "change" },
        ],
        quality: [{ required: true, message: "请选择图片", trigger: "change" }],
        price: [{ required: true, message: "请填写价格", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getSupermarketNameList();
    this.getList();
  },
  methods: {
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      let queryshelfTime ,querydownTime, query;
       
       queryshelfTime = this.addDateRange(this.queryParams, this.dateRange.shelfTime,'ShelfTime');    
         querydownTime = this.addDateRange(queryshelfTime, this.dateRange.downTime,'DownTime');      
         query = this.addDateRange(querydownTime, this.dateRange.expiratTime,'ExpiratTime');
         console.log('query',query);           
      listCommodity(query).then((response) => {
        this.commodityList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        supermarketId: null,
        name: null,
        classificationId: null,
        price: null,
        shelfTime: null,
        downTime: null,
        expiratTime: null,
        ownRegionId: null,
        picture: null,
        quality: null,
        qualityUnit: null,
        inventoryUnit: null,
        inventory: null,
        producer: null,
        brand: null,
        delFlag: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remarks: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = {
        shelfTime: [],
          downTime: [],
          expiratTime: [],
      }
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 初始化超市名称
    getSupermarketNameList() {
      if (this.$store.getters.userId == 0) {
        return;
      }
      const userId = this.$store.getters.userId;
      getSupermarketName(userId).then((response) => {
        this.supermarketOptions = response.data;
      });
      getRegionName(userId).then((response) => {
        this.regionOptions = response.data;
      });
      getClassificationName(userId).then((response) => {
        this.classificationOptions = response.data;
      });
    },

    //根据超市id查询分类名称与区域名称
     hangleNameBySupermarketId(){
      // this.form.classificationId = null;
      // this.form.ownRegionId = null;
      this.newRegionOptions = this.regionOptions.filter(element =>
         element.supermarketId == this.form.supermarketId);

         this.newClassificationOptions = this.classificationOptions.filter(element =>
         element.supermarketId == this.form.supermarketId);
     },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCommodity(id).then((response) => {
        this.form = response.data;
        this.hangleNameBySupermarketId();
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCommodity(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCommodity(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除商品编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCommodity(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "shop/commodity/export",
        {
          ...this.queryParams,
        },
        `commodity_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped>

.search el-option .select {
  width: 55px;
}
.search {
  width: 60px;
}
</style>